<template>
  <div class="app-main">
    <div class="app-main-left">
      <groups-tree @tree="getTreeData" @selectedKeys="getSelectedKeys" />
    </div>
    <div class="app-main-right">
      <a-card :bordered="false">
        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <div>
            <a-button type="primary" @click="handleRecord('add')">新增网格员</a-button>
            <a-button @click="handleExportXls()" :loading="confirmLoading"><a-icon type="upload" />导出</a-button>
            <a-button @click="handleImportXls" v-has="'gridMember:import'"><a-icon type="import" />导入</a-button>
            <a @click="dowloadsXls" v-has="'gridMember:import'">下载导入模板</a>
          </div>
        </div>
        <!-- 表格展示 -->
        <div class="table-page-content">
          <z-table
            ref="table"
            rowKey="id"
            :showAlert="false"
            :showSelection="false"
            :loading="loading"
            :columns="columns"
            :dataSource="pageData"
            @change="onTableChange"
          />
        </div>
        <!--弹窗区域-->
        <change-pwd-modal ref="passwordModalRef" />
        <edit-modal ref="editModalRef" :title="title" :treeDatas="treeDatas" @ok="onQuery" />
        <details-modal ref="detailsModalRef" :title="title" />
        <import-modal ref="importModal" :url="importUrl" :rolesOptions="rolesOptions" @ok="onQuery" />
      </a-card>
    </div>
  </div>
</template>

<script>
import * as structureApi from '@/api/xlgc/structure.js'
import { queryall } from '@/api/api'
import { downLoadFileReader } from '@/utils/export-util/util'
import groupsTree from './modules/groupsTree'
import editModal from './modules/editModal'
import detailsModal from './modules/detailsModal'
import changePwdModal from './modules/changePwdModal'
import importModal from './modules/importModal'

export default {
  components: {
    groupsTree,
    editModal,
    detailsModal,
    changePwdModal,
    importModal
  },
  data() {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      title: null,
      loading: false,
      confirmLoading: false,
      rolesOptions: [],
      form: {},
      treeDatas: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'order',
          width: 60,
          align: 'center',
          customRender: (text, record, index) =>
            `${(this.pageFilter.pageNo - 1) * this.pageFilter.pageSize + (index + 1)}` // 序号分页后连续
        },
        {
          title: '网格员姓名',
          width: 80,
          align: 'center',
          dataIndex: 'realname',
          customRender: text => {
            return <j-ellipsis value={text} length={5} />
          }
        },
        {
          title: '角色',
          width: 130,
          align: 'center',
          dataIndex: 'roleName',
          customRender: text => {
            return <j-ellipsis value={text} length={12} />
          }
        },
        {
          title: '网格',
          dataIndex: 'departName',
          width: 130,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={12} />
          }
        },
        {
          title: '网格编号',
          dataIndex: 'departCode',
          width: 130,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={12} />
          }
        },
        {
          title: '创建人',
          dataIndex: 'createBy',
          width: 80,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={5} />
          }
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          width: 80,
          align: 'center'
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: 70,
          align: 'center',
          customRender: text => {
            return (
              <span class={'status status_' + text}>
                {text === 1 ? '使用中' : text === 2 ? '已停用' : ''}
              </span>
            )
          }
        },
        {
          title: '操作',
          width: 110,
          align: 'center',
          dataIndex: 'action',
          customRender: (text, record) => {
            return (
              <a-space size={0}>
                <a-button onClick={() => this.handleRecord('edit', record)} type="link" style="padding:0;">编辑</a-button>
                <a-divider type="vertical" />
                <a-button onClick={() => this.handleRecord('details', record)} type="link" style="padding:0;">查看</a-button>
                <a-divider type="vertical" />
                <a-button onClick={() => this.handleAccount(record)} type="link" style={record.status === 1 ? 'color:red;padding:0;' : 'padding:0;'}>
                  {record.status === 1 ? '停用' : '启用'}
                </a-button>
                <a-divider type="vertical" />
                <a-button onClick={() => this.handlePwd(record)} type="link" style="padding:0;">修改密码</a-button>
              </a-space>
            )
          }
        }
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10
      },
      pageData: {}
    }
  },
  computed: {
    importUrl() {
      return structureApi.userImportUrl
    }
  },
  async mounted() {
    this.onQuery()
    this.initRoleList()
  },
  methods: {
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      this.form = {}
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
    },
    onTableChange(pagination, pageFilter, sorter) {
      let keyMap = { currentPage: 'pageNo' }
      let paginations = Object.keys(pagination).reduce((newData, key) => {
        let newKey = keyMap[key] || key
        newData[newKey] = pagination[key]
        return newData
      }, {})
      this.pageFilter = Object.assign({}, this.pageFilter, paginations)
      this.refreshTable()
    },
    refreshTable() {
      let form = Object.assign({}, this.form, this.pageFilter)
      this.loading = true
      structureApi
        .listWGY(form)
        .then(res => {
          if (res.success) {
            this.pageData = res.result ? res.result : {}
            this.loading = false
            this.$refs.table.onClearRowKeys()
          } else {
            this.loading = false
          }
        })
        .catch(e => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    // 新增用户、编辑用户、用户详情
    handleRecord(status, record) {
      this.title = status === 'add' ? '新增网格员' : status === 'edit' ? '编辑网格员' : status === 'details' ? '网格员详情' : ''
      if (status === 'add') {
        this.$refs.editModalRef.add()
        if (Object.keys(this.form).length > 0 && this.form.departId) {
          this.$set(this.$refs.editModalRef.form, 'selectedDeparts', this.form.departId)
        }
      } else if (status === 'edit') {
        this.$refs.editModalRef.edit(record)
      } else if (status === 'details') {
        this.$refs.detailsModalRef.disableSubmit = true
        this.$refs.detailsModalRef.edit(record)
      }
    },
    // 启用、停用
    handleAccount(record) {
      let that = this
      let status = record.status === 1 ? 2 : record.status === 2 ? 1 : ''
      let statusTxt = record.status === 1 ? '停用' : record.status === 2 ? '启用' : ''
      this.$confirm({
        title: `确定要${statusTxt}该帐号吗？`,
        okText: '确定',
        cancelText: '关闭',
        onOk() {
          structureApi.account({ id: record.id, status: status }).then(res => {
            if (res.success) {
              that.$message.success(res.message ? res.message : `${statusTxt}成功`)
              that.refreshTable()
            } else {
              that.$message.warn(res.message ? res.message : `${statusTxt}失败`)
            }
          })
          .catch(e => {
            that.$message.warn('操作失败！')
          })
        }
      })
    },
    // 修改密码
    handlePwd(record) {
      this.$refs.passwordModalRef.edit(record)
    },
    // 导出
    handleExportXls() {
      this.confirmLoading = true
      let form = Object.assign({}, this.form)
      structureApi.exports(form).then(async res => {
        const fileName = '组织架构-网格员.xlsx'
        await downLoadFileReader(res, fileName)
        this.confirmLoading = false
      })
    },
    // 导入
    dowloadsXls() {
      // structureApi.imports().then(res => {
      //   if (res.success) {
          const url = '/personnel.xlsx'
          if (!url) return
          const elt = document.createElement('a')
          elt.setAttribute('href', url)
          elt.download = '网格员导入模板.xlsx'
          elt.style.display = 'none'
          document.body.appendChild(elt)
          elt.click()
          document.body.removeChild(elt)
        // } else {
        //   this.$message.warn('模板下载失败！')
        // }
      // })
      // .catch(e => {
      //   this.$message.warn('请求失败！')
      // })
    },
    handleImportXls() {
      this.$refs.importModal.show()
    },
    // 初始化角色字典
    initRoleList() {
      queryall().then((res) => {
        if (res.success) {
          this.rolesOptions = res.result.map((item, index, arr) => {
            let c = { label: item.roleName, value: item.id }
            return c
          })
          console.log('this.rolesOptions: ', this.rolesOptions)
        }
      })
    },
    getSelectedKeys(keys) {
      console.log(keys)
      this.$set(this.form, 'departId', keys.join(','))
      this.onQuery()
    },
    getTreeData(datas) {
      this.treeDatas = datas
    }
  }
}
</script>
<style lang="less" scoped>
.app-main {
  display: flex;
  flex-direction: row;
  align-items: stretch;
  border: 1px #e8e8e8 solid;
  background-color: #fff;
}
.app-main-left {
  flex: 0 0 300px;
  flex-direction: column;
  display: flex;
  border-right: 1px #e8e8e8 solid;
  background-color: #fff;
}
.app-main-right {
  width: 100%;
  flex-direction: column;
  display: flex;
}
.status {
  display: flex;
  align-items: center;
  justify-content: center;
  &::before {
    content: '';
    width: 6px;
    height: 6px;
    margin-right: 2px;
    display: block;
    border-radius: 50%;
  }
  &.status_1 {
    color: #70B603;
    &::before {
      background-color: #70B603;
    }
  }
  &.status_2 {
    color: #AAAAAA;
    &::before {
      background-color: #AAAAAA;
    }
  }
}
</style>
